Passed
Push — master ( 0ad226...768538 )
by Plamen
01:28
created

table.js ➔ TableHelperDraw_SectionClear   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 11
rs 10
1
var TableHelper = {};
2
TableHelper.Init = {
3
    SetColumnsHoverEffect: function (tContainer, tableId){
4
        var tHcells = tContainer.rows[0].cells;
5
        for(var i = 0; i < tHcells.length; i++){
6
            if(tHcells[i].firstChild.tagName === "A"){
7
                tHcells[i].firstChild.setAttribute("onmouseover", "table.ColumnHover('" + tableId + "'," + i + ");");
8
                tHcells[i].firstChild.setAttribute("onmouseout", "table.ColumnHover('" + tableId + "');");
9
            }
10
        }
11
    }
12
};
13
TableHelper.BuildRequest = {
14
    Sort: function (rq, strDesc){
15
        function sortBySpan(span, i){
16
            var order = span.innerHTML;
17
            if(order.length === 1){
18
                rq.colNo = i;
19
                rq.colOrd = order === strDesc ? "desc" : "asc";
20
            }
21
            return rq.colNo === i;
22
        }
23
24
        var thTags = document.getElementById(rq.tableId)
25
                .getElementsByTagName("thead")[0]
26
                .getElementsByTagName("th");
27
        var length = thTags.length;
28
        for(var i = 0; i < length; i++){
29
            var link = thTags[i].getElementsByTagName("a")[0];
30
            if(link){
31
                var span = link.getElementsByTagName("span")[0];
32
                if(span && sortBySpan(span, i)){
33
                    break;
34
                }
35
            }
36
        }
37
    },
38
    Filter: function (rq){
39
        function getFilterFieldsByTableID(tableID){
40
            var fields = {filterBy: null, filter: null};
41
            var filterDiv = getFilterDivByTableIDOrNull(tableID);
42
            if(filterDiv !== null){
43
                setFilterBy(fields, filterDiv);
44
                setFilterValue(fields, filterDiv);
45
            }
46
            return fields;
47
        }
48
        function getFilterDivByTableIDOrNull(tableID){
49
            var res = null;
50
            if(document.getElementById(tableID).parentNode.getElementsByTagName("div").length > 0){
51
                for(var i = 0; i < document.getElementById(tableID).parentNode.getElementsByTagName("div").length; i++){
52
                    if(document.getElementById(tableID).parentNode.getElementsByTagName("div")[i].getAttribute("class") === "filter"){
53
                        return document.getElementById(tableID).parentNode.getElementsByTagName("div")[i];
54
                    }
55
                }
56
57
            }
58
            return res;
59
        }
60
        function setFilterBy(fields, filterDiv){
61
            var slctObj = filterDiv.getElementsByTagName("select")[0];
62
            if(slctObj && slctObj.options[slctObj.selectedIndex].value !== "all"){
63
                fields.filterBy = slctObj.options[slctObj.selectedIndex].value;
64
            }
65
        }
66
        function setFilterValue(fields, filterDiv){
67
            var textObj = filterDiv.getElementsByTagName("input")[0];
68
            if(textObj && textObj.value && textObj.value.length !== 0){
69
                fields.filter = encodeURIComponent(textObj.value.trim());
70
            }
71
        }
72
73
        var r = getFilterFieldsByTableID(rq.tableId);
74
        if(r.filter !== null){
75
            rq.filter = r.filter;
76
        }
77
        if(r.filterBy !== null){
78
            rq.filterBy = r.filterBy;
79
        }
80
    }
81
};
82
TableHelper.ProcessPaginationLinks = function(tfoot){
83
    var pLinks = tfoot.querySelectorAll(".paging a");
84
    if(pLinks.length > 0){
85
        for(var j = 0; j < pLinks.length; j++){
86
            pLinks[j].setAttribute("href", "javascript:void(0);");
87
            pLinks[j].setAttribute("onclick", "return table.GoPage(this);");
88
        }
89
    }
90
};
91
92
var TableHelperColumnHover = function(tableContainer, index){
93
    var rows = document.getElementById(tableContainer).rows;
94
    var upto = rows.length - 1;
95
    if(typeof index === "undefined"){
96
        TableHelperColumnHoverRelease(rows, upto);
97
    } else {
98
        for(var i = 0; i < upto; i++){
99
            rows[i].cells[index].setAttribute("lang", "col-hover");
100
        }
101
    }
102
};
103
var TableHelperColumnHoverRelease = function(rows, upto){
104
    for(var i = 0; i < upto; i++){
105
        for(var j = 0; j < rows[i].cells.length; j++){
106
            if(rows[i].cells[j].lang){
107
                rows[i].cells[j].removeAttribute("lang");
108
            }
109
        }
110
    }
111
};
112
var TableHelperSetVisability = function(tableContainer, flag){
113
    var tbl = document.getElementById(tableContainer);
114
    if(flag === true){
115
        tbl.style.filter = "none";
116
        tbl.style.opacity = "1";
117
        tbl.style.cursor = "auto";
118
    }else if(flag === false){
119
        tbl.style.filter = "blur(1px)";
120
        tbl.style.opacity = "0.8";
121
        tbl.style.cursor = "wait";
122
    }else{
123
        console.error("table error in the flag value");
124
    }
125
};
126
127
var TableHelperGoPageGetNo = function(lnk, tableId){
128
    //check & serve pagination jump links
129
    var jumpDir = lnk.innerHTML.trim().substr(0, 1);
130
    if(jumpDir === "+" || jumpDir === "-"){
131
        var current = document.getElementById(tableId)
132
                        .querySelector("tfoot .paging .a").innerHTML;
133
        var jump = lnk.innerHTML.replace("K", "000").replace("M", "000000000");
134
        var jumpPage = (parseInt(current) + parseInt(jump));
135
        lnk.parentNode.setAttribute("data-page", jumpPage);
136
        lnk.style.transform = "none";
137
    }
138
    return lnk.parentNode.hasAttribute("data-page") ?
139
            lnk.parentNode.getAttribute("data-page") :
140
            lnk.innerHTML;
141
};
142
var TableHelperIePrior = function(v){
143
    var rv = false;
144
    if(window.navigator.appName === 'Microsoft Internet Explorer'){
145
        var ua = window.navigator.userAgent;
146
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
147
        if(re.exec(ua) !== null){
148
            rv = parseFloat(RegExp.$1);
149
        }
150
        rv = rv < v ? true : false;
151
    }
152
    return rv;
153
};
154
var TableHelperRequestToUrl = function(rq){
155
    var url = location.pathname + ".json" + location.search;
156
    if(typeof rq === "object"){
157
        var getUrlVarName = {
158
            colNo: "col", colOrd: "ord", filter: "filter",
159
            filterBy: "filter-by", pageNo: "pg", exportType: "export",
160
            tableId: "table-id"
161
        };
162
        var flagFirst = location.search.length < 1 ? true : false;
163
        for(var r in rq){
1 ignored issue
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
164
            var clue = flagFirst === true ? "?" : "&";
165
            url += clue + getUrlVarName[r] + "=" + rq[r];
166
            flagFirst = false;
167
        }
168
    }
169
    return url;
170
};
171
var TableHelperGetParent = function(obj, objType){
172
    while(obj && obj.tagName !== objType.toUpperCase()){
173
        obj = obj.parentNode;
174
    }
175
    return obj;
176
};
177
var TableHelperFilterGetTableId = function(field){
178
    if(field.tagName.toLowerCase() !== "select"){
179
        return field.getAttribute("data-table-id");
180
    }
181
    var f = field.parentNode.parentNode.getElementsByTagName("input")[0];
182
    return '' === f.value ? null : f.getAttribute("data-table-id");
183
};
184
var TableHelperDraw_Section = function(tableContainer, dt, tSection){
185
    var section = tSection === "tfoot" ? "tfoot" : "tbody";
186
    var tSec = document.getElementById(tableContainer)
187
                .getElementsByTagName(section)[0];
188
    TableHelperDraw_SectionClear(tSec, TableHelperIePrior(9));
189
    for(var i = 0; i < dt.length; i++){
190
        var row = dt[i];
191
        var tRow = document.createElement("tr");
192
        TableHelperDraw_SectionRow(row, tRow);
193
        tSec.appendChild(tRow);
194
        if(section === "tfoot"){
195
            TableHelper.ProcessPaginationLinks(tSec);
196
        }
197
    }
198
};
199
var TableHelperDraw_SectionClear = function(tSection, iePrior9){
200
    if(iePrior9){
201
        if(tSection.firstChild){
202
            while(tSection.firstChild){
203
                tSection.removeChild(tSection.firstChild);
204
            }
205
        }
206
    }else{
207
        tSection.innerHTML = "";
208
    }
209
};
210
var TableHelperDraw_SectionRow = function(row, tRow){
211
    for(var cell in row){
1 ignored issue
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
212
        var tCell = document.createElement("td");
213
        if(typeof row[cell] === "string" || typeof row[cell] === "number"){
214
            tCell.innerHTML = row[cell];
215
        }else if(typeof row[cell] === "object"){
216
            TableHelperDraw_SectionRowCellFromObject(row, cell, tCell);
217
        }
218
        tRow.appendChild(tCell);
219
    }
220
};
221
var TableHelperDraw_SectionRowCellFromObject = function(row, cell, tCell){
222
    for(var attr in row[cell]){
1 ignored issue
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
223
        if(typeof row[cell][attr] === "string"){
224
            tCell.innerHTML = row[cell][attr];
225
        }else if(typeof row[cell][attr] === "object"){
226
            for(var v in row[cell][attr]){
1 ignored issue
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
227
                tCell.setAttribute(v, row[cell][attr][v]);
228
            }
229
        }
230
    }
231
};
232
233
//https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
234
var TableSingleton = (function(){
235
    // Instance stores a reference to the Singleton
236
    var instance;
237
    function initInstance(){
238
        // Singleton
239
        // Private methods and variables
240
        var tail = null;
241
        function Init(tableId){
242
            var tContainer = document.getElementById(tableId);
243
            if(iePrior(9)){
244
                TableHelper.Init.SetColumnsHoverEffect(tContainer, tableId);
245
            }
246
            var tfoot = tContainer.getElementsByTagName("tfoot")[0];
247
            TableHelper.ProcessPaginationLinks(tfoot);
248
        }
249
        function BuildRequest(rq, crntTableId, strDesc){
250
            rq.tableId = crntTableId;
251
            TableHelper.BuildRequest.Sort(rq, strDesc);
252
            TableHelper.BuildRequest.Filter(rq);
253
        };
254
        function LoadData(tableContainer, rq){
255
            if(tail!==null){ tail.abort();}
256
            TableHelperSetVisability(tableContainer, false);
257
            var xmlhttp = window.XMLHttpRequest ? 
258
                            new XMLHttpRequest() : /* code for IE7+, Firefox, Chrome, Opera, Safari */
259
                            new window.ActiveXObject("Microsoft.XMLHTTP");/*code for IE6, IE5 */
260
            xmlhttp.onreadystatechange = function(){
261
                if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
262
                    Draw(tableContainer, JSON.parse(xmlhttp.responseText));
263
                    TableHelperSetVisability(tableContainer, true);
264
                    instance.LoadEndCalback(tableContainer);
265
                }
266
            };
267
            xmlhttp.open("GET", RequestToUrl(rq), true);
268
            xmlhttp.send();
269
            tail = xmlhttp; //put at tail to can abort later any previous
270
        }
271
        function Draw(tableContainer, d){
272
            TableHelperDraw_Section(tableContainer, d.body);
273
            TableHelperDraw_Section(tableContainer, d.footer, "tfoot");
274
            if(instance.rq !== null){
275
                var hover = document.getElementById(instance.rq.tableId)
276
                            .getElementsByTagName("th")[instance.rq.colNo].lang;
277
                if(hover){
278
                    instance.ColumnHover(tableContainer, instance.rq.colNo);
279
                }
280
            }
281
        }
282
283
        var FilterGetTableId = TableHelperFilterGetTableId;
284
        var GoPageGetNo = TableHelperGoPageGetNo;
285
        var getParent = TableHelperGetParent;
286
        var iePrior = TableHelperIePrior;
287
        var RequestToUrl = TableHelperRequestToUrl;
288
289
        return {
290
            rq: null,
291
            strAsc: String.fromCharCode(9650), //&#9650;
292
            strDesc: String.fromCharCode(9660),//&#9660; 
293
            ReloadData: function(tableId){
294
                var request = {};
295
                BuildRequest(request, tableId, this.strDesc);
296
                LoadData(tableId, request);
297
            },
298
            Filter: function(field){
299
                var crntTableId = FilterGetTableId(field);
300
                if(crntTableId !== null){
301
                    var request = {};
302
                    var exRq = this.rq;
303
                    BuildRequest(request, crntTableId, this.strDesc);
304
                    if(exRq === null ||
305
                        request.filter !== exRq.filter ||
306
                        request.filterBy !== exRq.filterBy
307
                    ){
308
                        LoadData(crntTableId, request);
309
                    }
310
                }
311
            },
312
            GoPage: function(lnk){
313
                var request = {};
314
                var crntTableId = getParent(lnk, "table").getAttribute("id");
315
                BuildRequest(request, crntTableId, this.strDesc);
316
                request.pageNo = GoPageGetNo(lnk, crntTableId);
317
                LoadData(crntTableId, request);
318
                return false;
319
            },
320
            Export: function(lnk, eType){
321
                var request = {};
322
                var crntTableId = getParent(lnk, "table").getAttribute("id");
323
                BuildRequest(request, crntTableId, this.strDesc);
324
                request.exportType = ["CSV", "Excel"].indexOf(eType) >= 0 ?
325
                                        eType : 
326
                                        "csv";
327
                window.open(RequestToUrl(request));
328
                return false;
329
            },
330
            Sort: function(colNo, lnk){
331
                var request = {};
332
                var crntTableId = getParent(lnk, "table").getAttribute("id");
333
                BuildRequest(request, crntTableId, this.strDesc);
334
                if(Math.round(colNo) === request.colNo){
335
                    request.colOrd = (request.colOrd === "asc" ? "desc" : "asc");
336
                }else{
337
                    request.colNo = Math.round(colNo);
338
                    request.colOrd = "asc";
339
                }
340
                LoadData(crntTableId, request);
341
                /* Clear and add new sort arrow */
342
                var headSpans = getParent(lnk, "thead").getElementsByTagName("span");
343
                var length = headSpans.length;
344
                for(var i = 0; i < length; i++){
345
                    headSpans[i].innerHTML = "";
346
                }
347
                lnk.getElementsByTagName("span")[0].innerHTML = (request.colOrd === "desc" ? this.strDesc : this.strAsc);
348
            },
349
            ColumnHover: function(tableContainer, index){
350
                if(!iePrior(9)){
351
                    TableHelperColumnHover.call(this, tableContainer, index);
352
                }
353
            },
354
            LoadEndCalback: function(){},/*Allows override: function(tableId){if(tableId){...}}*/
355
            init: Init
356
        };
357
    }
358
    return {
359
        //Get the Singleton instance if one exists, or create one if it doesn't
360
        getInstance: function(){
361
            if(!instance){
362
                instance = initInstance();
363
            }
364
            return instance;
365
        }
366
    };
367
})();
368
var table = TableSingleton.getInstance();
369